package com.vshop.platform.system.crud.dao;

import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.vshop.platform.system.domain.entity.SysUserPost;
import com.vshop.platform.system.crud.mapper.SysUserPostMapper;
import org.springframework.stereotype.Repository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import static com.vshop.platform.system.domain.entity.table.SysUserPostTableDef.SysUserPostTable;


/**
 * 用户与岗位关联表 服务层实现。
 *
 * @author vshop
 * @since 2024-11-18
 */
@RequiredArgsConstructor
@Slf4j
@Repository
public class SysUserPostDao extends ServiceImpl<SysUserPostMapper, SysUserPost> {
    /**
     * 通过用户ID查询岗位数量
     *
     * @param userId 用户ID
     * @return 结果
     */
    public List<Long> listPostIdByUserId(Long userId) {
        QueryWrapper queryWrapper = QueryWrapper.create()
                .select(SysUserPostTable.PostId)
                .from(SysUserPostTable)
                .where(SysUserPostTable.UserId.eq(userId));
        return listAs(queryWrapper, Long.class);
    }


    /**
     * 保存用户岗位信息关联
     *
     * @param userId  用户ID
     * @param postIds 新增的岗位ID列表
     */
    public void saveUserPost(Long userId, List<Long> postIds) {
        boolean inserted = true;
        List<SysUserPost> list = new java.util.ArrayList<>();
        // 新增用户与岗位管理
        for (Long postId : postIds) {
            SysUserPost up = new SysUserPost();
            up.setUserId(userId);
            up.setPostId(postId);
            list.add(up);
        }
        this.saveBatch(list, 100);
    }


    /**
     * 通过用户ID删除用户和岗位关联
     * delete from sys_user_post where user_id=#{userId}
     *
     * @param userId 用户ID
     */
    public void removeUserPostByUserId(Long userId) {
        QueryWrapper queryWrapper = query().where(SysUserPostTable.UserId.eq(userId));
        this.remove(queryWrapper);
    }

    /**
     * 批量删除用户和岗位关联
     * delete from sys_user_post where user_id in
     *
     * @param userIds 需要删除的数据ID
     */
    public void removeUserPostByUserIds(List<Long> userIds) {
        QueryWrapper queryWrapper = query().where(SysUserPostTable.UserId.in(userIds));
        this.remove(queryWrapper);
    }

}
